/**
	zc company ftp service module.
	author yeqin and zc teamson company reserved all copyright.
*/


const {FtpOperate} = require("../FtpOperate")

//@Bean
class ZcFtpService {

	
	//@Autowired
	zcFtpServiceConfig;

	//encapsulate ftp client.
	ftpOperate;

	/**
		open the connect ftp service.
		()=>void
	*/
	async connect(){
		//gain the client instance for ftp operation
		const client = await this.zcFtpServiceConfig.doConnect();
		//futher encapsulation ftp regular operation.
		this.ftpOperate = new FtpOperate(client);
		return this.ftpOperate;
	}


	/**
		logout from the ftp service of the target host.
	*/
	async close(){
		if(this.zcFtpServiceConfig.isConnect){

			this.zcFtpServiceConfig.close();
		}
	}

	getOperate(){
		return this.ftpOperate;
	}


	/**
		more secure call ftp service.
		automatically establish link and shut down the service.
		(Function(operate)) => Promise
	*/
	async safeInvoke(callback){

		try{

			if(!this.zcFtpServiceConfig.isConnect)
				await this.connect();

			await callback(this.ftpOperate);

			await this.ftpOperate.logout();

			await this.close();

		}catch(e){

			await this.close();

			throw e;
		}

	}

}

module.exports = {ZcFtpService}